<template>
	<view class="editCont">
		<u--form
			labelPosition="left"
			labelWidth="160rpx"
			:model="form"
			ref="uForm"
		>
			<u-form-item
				label="类型"
				prop="type"
				borderBottom
			>
				<u-radio-group
				    v-model="form.type"
					style="flex-wrap: wrap;margin-top: 20rpx;"
				    @change="groupChange"
				>
				    <u-radio
						v-for="(item, index) in hairTypes"
						:key="index"
						:label="item.name"
						:name="item.name"
						:disabled="!!detailId"
				    >
				    </u-radio>
				</u-radio-group>
			</u-form-item>
			<u-form-item
				label="标题"
				prop="title"
				borderBottom
			>
				<u--input
					v-model="form.title"
					:maxlength="10"
					border="none"
					placeholder="请输入标题(不超过10个字)"
					clearable
				></u--input>
			</u-form-item>
			<u-form-item
				label="毛坯价格"
				prop="price_mp"
				borderBottom
			>
				<u--input
					v-model="form.price_mp"
					type="number"
					border="none"
					placeholder="请输入价格"
					clearable
				>
					<u-text
						text="￥"
						slot="prefix"
						margin="0 3px 0 0"
						type="tips"
					></u-text>
				</u--input>
			</u-form-item>
			<u-form-item
				label="成品价格"
				prop="price_cp"
				borderBottom
			>
				<u--input
					v-model="form.price_cp"
					type="number"
					border="none"
					placeholder="请输入价格"
					clearable
				>
					<u-text
						text="￥"
						slot="prefix"
						margin="0 3px 0 0"
						type="tips"
					></u-text>
				</u--input>
			</u-form-item>
			<u-form-item
				label="烫发价格"
				prop="price_tp"
				borderBottom
			>
				<u--input
					v-model="form.price_tp"
					type="number"
					border="none"
					placeholder="请输入价格"
					clearable
				>
					<u-text
						text="￥"
						slot="prefix"
						margin="0 3px 0 0"
						type="tips"
					></u-text>
				</u--input>
			</u-form-item>
			<u-form-item
				label="尺寸"
				prop="stocks"
				borderBottom
			>
				<view style="width: 100%;" class="flex flex-wrap">
					<view class="flex-sub">
						<text v-if="!form.stocks.length" class="u-tips-color">暂无尺寸信息</text>
						<view class="flex-sub flex flex-wrap">
							<view
								v-for="(tag, i) in form.stocks"
								:key="i" 
								class="tag" >
								<u-tag
									:text="tag.name" 
									borderColor="#f4f5f7" 
									bgColor="#f4f5f7" 
									color="#999" 
									size="mini"></u-tag>
							</view>
						</view>
					</view>
					<!-- <u-icon name="arrow-down" color="#888" size="20"></u-icon> -->
					<u-icon @click="addTag" class="icon" color="#3c9cff" name="edit-pen" size="24"></u-icon>
				</view>
			</u-form-item>
			<u-form-item
				label="图片"
				borderBottom
			>
				<view class="flex flex-wrap">
					<view v-for="(item, index) in form.images" :key="index" class="uploadGroup">
						<u--image 
							:showLoading="true" 
							:src="item" 
							class="image"
							width="80px" 
							height="80px" ></u--image>
						<view @click="deletePic(index)" class="iconbox">
							<u-icon class="icon" name="close" color="#fff" size="20"></u-icon>
						</view>
					</view>
					<u-upload
						@afterRead="afterRead"
						multiple
						:maxCount="9"
					></u-upload>
				</view>
			</u-form-item>
			<!-- <u-form-item
				v-if="detailId"
				label="库存"
				prop="title"
				borderBottom
			>
				<u-button  type="primary" @click="viewStock">查看库存</u-button>
			</u-form-item> -->
		</u--form>
		
		<view class="actionsFix">
			<u-button 
				class="btn" 
				plain 
				type="primary" 
				:loading="saveLoading"
				@click="submit">保存</u-button>
		</view>
		
		<!-- 编辑尺寸 -->
		<u-popup :show="showSize" @close="closeTagPop" @open="openTagPop">
			<view class="sizeBox">
				<view class="title">编辑尺寸</view>
				<view class="inner flex flex-wrap">
					<u-tag
						v-for="(tag, i) in allSizes" 
						:key="i" 
						:show="tag.checked"
						@close="delTag(i)"
						closable
						class="tag" 
						size="large"
						:text="tag.name" 
						borderColor="#f4f5f7" 
						bgColor="#f4f5f7" 
						color="#999"></u-tag>
				</view>
			</view>
			<view class="sizeAction flex m-t-30">
				<u--input
					v-model="singleSize"
					type="text"
					placeholder="请输入规格"
					clearable
					class="flex-sub"
				></u--input>
				<u-button 
					class="btn" 
					plain 
					type="primary" 
					:custom-style="{width: '160rpx',marginLeft: '30rpx'}"
					@click="submitTag">添加</u-button>
			</view>
		</u-popup>
	</view>
</template>

<script>
	const db = uniCloud.database()
	const uniCloudStorageExtCo = uniCloud.importObject('ext-storage-co')
	
	export default {
		data() {
			return {
				detailId: '',
				
				hairTypes: [],
				form: {
					type: '60网',
					title: '',
					price_mp: '',
					price_cp: '',
					price_tp: '',
					stocks: [],
					images: []
				},
				fileList: [],
				saveLoading: false,
				
				showSize: false,
				singleSize: '',
				allSizes: [],
			}
		},
		onReady() {
			// uni.$on('refreshStock', (data) => {
			// 	console.log(data)
			// })
		},
		onLoad(options) {
			this.detailId = options.id
			if (this.detailId) {
				this.getDetail()
			}
			this.getTypes()
			uni.setNavigationBarTitle({
				title: `${this.detailId ? '编辑' : '添加'}类型`
			})
		},
		methods: {
			getTypes() {
				db.collection('hxs-types').get().then(res => {
					this.hairTypes = res.result.data
				})
			},
			getDetail() {
				uni.showLoading({
					title: '数据加载中...'
				})
				db.collection('hxs-list').doc(this.detailId).get().then(res => {
					let { data } = res.result
					if (data.length) {
						let obj = data[0]
						this.form.type = obj.type
						this.form.title = obj.title
						this.form.price_cp = obj.price_cp
						this.form.price_mp = obj.price_mp
						this.form.price_tp = obj.price_tp
						this.form.stocks = obj.stocks || []
						this.form.images = obj.images || []
					}
				}).finally(() => {
					uni.hideLoading()
				})
			},
			
			groupChange(e) {
				console.log(e)
			},
			
			// 编辑尺寸
			addTag() {
				this.showSize = true
			},
			delTag(index) {
				this.allSizes.splice(index, 1)
			},
			openTagPop() {
				let arr = this.form.stocks.map(item => {
					return {
						...item,
						checked: true
					}
				})
				this.allSizes = arr
			},
			closeTagPop() {
				let arr = this.allSizes.map(item => {
					return {
						name: item.name,
						value: item.value | 0
					}
				})
				this.form.stocks = arr
				this.showSize = false
			},
			submitTag() {
				let arr = this.singleSize.split(',')
				arr.forEach(item => {
					this.allSizes.push({
						name: item,
						checked: true
					})
				})
				this.allSizes.sort((a, b) => {
				  let partsA = a.name.split('/').map(Number)
				  let partsB = b.name.split('/').map(Number)
				  return partsA[0] - partsB[0] || partsA[1] - partsB[1]
				})
				this.singleSize = ''
			},
			
			// 新增图片
			afterRead(event) {
				uni.showLoading({
					title: '图片上传中...'
				})
				let lists = [].concat(event.file)
				this.uploadImages(lists, 0)
			},
			async uploadImages(urls, index) {
				if (index >= urls.length) {
					// 所有图片上传完毕
					uni.hideLoading()
				    return
				}
				const item = urls[index]
				const uploadFileOptionsRes = await uniCloudStorageExtCo.getUploadFileOptions({
					cloudPath: `hxs/${Date.now()}.jpg`, // 支持自定义目录
				})
				const uploadTask = uni.uploadFile({
					...uploadFileOptionsRes.uploadFileOptions,
					filePath: item.url,
					success: () => {
						const res = {
							cloudPath: uploadFileOptionsRes.cloudPath, // 文件云端路径
							fileID: uploadFileOptionsRes.fileID, // 文件ID
							fileURL: uploadFileOptionsRes.fileURL, // 文件URL（如果是私有权限，则此URL是无法直接访问的）
						}
						// 数据库里可直接保存 fileURL 或 fileID
						// console.log("上传成功", res)
						this.form.images.push(uploadFileOptionsRes.fileURL)
						this.uploadImages(urls, index + 1)
					},
					fail: (err) => {
						console.log("上传失败", err)
						uni.hideLoading()
					}
				})
				uploadTask.onProgressUpdate((res) => {
					// console.log("监听上传进度", res);
				})
			},
			uploadFun(item) {
				return uniCloud.uploadFile({
					filePath: item.url,
					cloudPath: 'hxspic'
				})
			},
			deletePic(index) {
				this.form.images.splice(index, 1)
			},
			
			viewStock() {
				uni.navigateTo({
					url: '/pages/stock/stock?id=' + this.detailId
				})
			},
			
			// 保存
			submit() {
				if (!this.form.title) {
					uni.$u.toast('请输入标题')
					return
				}
				if (!this.form.price_mp) {
					uni.$u.toast('请输入毛坯价格')
					return
				}
				if (!this.form.price_cp) {
					uni.$u.toast('请输入成品价格')
					return
				}
				if (!this.form.price_tp) {
					uni.$u.toast('请输入烫发价格')
					return
				}
				if (!this.form.stocks || !this.form.stocks.length) {
					uni.$u.toast('请添加尺寸')
					return
				}
				this.saveLoading = true
				
				let obj = { ...this.form }
				let httpUrl = ''
				if (this.detailId) {
					obj._id = this.detailId
					obj.updatetime = Date.now()
					// console.log(obj)
					
					httpUrl = db.collection('hxs-list').doc(this.detailId).update({
						title: obj.title,
						price_mp: obj.price_mp,
						price_cp: obj.price_cp,
						price_tp: obj.price_tp,
						stocks: obj.stocks,
						images: obj.images,
						updatetime: obj.updatetime
					})
				} else {
					obj.createtime = Date.now()
					
					httpUrl = db.collection('hxs-list').add({
						...obj
					})
				}
				httpUrl.then(res => {
					uni.$u.toast('保存成功')
					setTimeout(() => {
						uni.navigateBack()
						uni.$emit('refreshList')
					}, 1500)
				}).catch(() => {
					uni.$u.toast('操作失败')
				}).finally(() => {
					this.saveLoading = false
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
.editCont {
	padding: 0 40rpx 130rpx;
	/deep/ .u-radio {
		margin: 0 20rpx 20rpx 0;
	}
	
	.tag {
		margin: 8rpx;
	}
}
.sizeBox {
	padding: 0 30rpx;
	.title {
		font-size: 30rpx;
		padding: 30rpx 0;
	}
	.inner {
		max-height: 60vh;
		overflow-y: auto;
	}
}
.sizeAction {
	padding: 0 30rpx 30rpx;
}
</style>
